<template>
    <div class="inbound-statistics-container">
        <!-- 统计卡片 -->
        <div class="statistics-cards">
            <el-card class="stat-card">
                <div class="stat-value">{{ statistics.totalOrders }}</div>
                <div class="stat-label">入库单数量</div>
            </el-card>
            <el-card class="stat-card">
                <div class="stat-value">{{ statistics.totalProducts }}</div>
                <div class="stat-label">入库货品数量</div>
            </el-card>
            <el-card class="stat-card">
                <div class="stat-value stat-value-green">{{ statistics.totalAmount }}</div>
                <div class="stat-label">入库货品金额</div>
            </el-card>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <el-button>导出</el-button>
            <el-button @click="handleRefresh">刷新</el-button>
            <el-button @click="showFieldInfo" type="info">📋 字段信息</el-button>
            <el-button @click="showApiInfo" type="warning">🔗 API信息</el-button>
        </div>

        <!-- 字段信息弹窗 -->
        <el-dialog v-model="fieldInfoVisible" title="📋 数据字段详情" width="80%" :close-on-click-modal="false">
            <div class="field-info-content">
                <el-tabs type="border-card">
                    <el-tab-pane label="🗂️ 数据字段映射">
                        <el-table :data="fieldMappings" border height="400">
                            <el-table-column label="序号" width="60" align="center">
                                <template #default="{ $index }">{{ $index + 1 }}</template>
                            </el-table-column>
                            <el-table-column label="显示名称" prop="displayName" width="150"
                                align="center"></el-table-column>
                            <el-table-column label="字段名" prop="fieldName" width="150" align="center">
                                <template #default="{ row }">
                                    <el-tag>{{ row.fieldName }}</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="数据类型" prop="dataType" width="100" align="center">
                                <template #default="{ row }">
                                    <el-tag :type="getTypeColor(row.dataType)">{{ row.dataType }}</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="说明" prop="description" show-overflow-tooltip></el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="🔢 当前数据示例">
                        <div v-if="tableData.length > 0" class="json-viewer">
                            <el-input type="textarea" :model-value="JSON.stringify(tableData[0], null, 2)" :rows="20"
                                readonly></el-input>
                        </div>
                        <el-empty v-else description="暂无数据"></el-empty>
                    </el-tab-pane>
                    <el-tab-pane label="📈 统计信息">
                        <div class="statistics-info">
                            <el-descriptions :column="2" border>
                                <el-descriptions-item label="总记录数">{{ tableData.length }}</el-descriptions-item>
                                <el-descriptions-item label="入库单数量">{{ statistics.totalOrders }}</el-descriptions-item>
                                <el-descriptions-item label="入库货品数量">{{ statistics.totalProducts
                                    }}</el-descriptions-item>
                                <el-descriptions-item label="入库货品金额">{{ statistics.totalAmount }}</el-descriptions-item>
                            </el-descriptions>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-dialog>

        <!-- API信息弹窗 -->
        <el-dialog v-model="apiInfoVisible" title="🔗 API接口信息" width="70%" :close-on-click-modal="false">
            <div class="api-info-content">
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="接口地址">
                        <el-tag type="primary">/api/ruku/items/list</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="请求方式">
                        <el-tag type="success">GET</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="当前参数">
                        <pre>{{ JSON.stringify(currentApiParams, null, 2) }}</pre>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </el-dialog>

        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%" v-loading="loading" height="600" :scroll-x="true"
            :scroll-y="true">
            <el-table-column type="selection" width="50" align="center" fixed="left"></el-table-column>
            <el-table-column prop="index" label="序号" width="70" align="center" fixed="left">
                <template #default="{ $index }">
                    {{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}
                </template>
            </el-table-column>

            <!-- 基础信息 -->
            <el-table-column label="记录ID" width="80" align="center">
                <template #default="{ row }">
                    {{ row.id || '' }}
                </template>
            </el-table-column>
            <el-table-column label="入库单ID" width="100" align="center">
                <template #default="{ row }">
                    {{ row.stockInOrderId || '' }}
                </template>
            </el-table-column>
            <el-table-column label="入库单号" width="140" align="center" fixed="left">
                <template #default="{ row }">
                    {{ row.stockInCode || '' }}
                </template>
            </el-table-column>

            <!-- 货品信息 -->
            <el-table-column label="货品ID" width="80" align="center">
                <template #default="{ row }">
                    {{ row.goodsId || '' }}
                </template>
            </el-table-column>
            <el-table-column label="货品编号" width="120" align="center">
                <template #default="{ row }">
                    {{ row.goodsCode || '' }}
                </template>
            </el-table-column>
            <el-table-column label="货品名称" width="150" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.goodsName || '' }}
                </template>
            </el-table-column>
            <el-table-column label="规格型号" width="120" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.specModel || row.specification || '' }}
                </template>
            </el-table-column>


            <!-- 库存和数量信息 -->
            <el-table-column label="当前库存" width="100" align="center">
                <template #default="{ row }">
                    {{ row.currentInventory || 0 }}
                </template>
            </el-table-column>
            <el-table-column label="进货数量" width="100" align="center">
                <template #default="{ row }">
                    {{ row.purchaseQuantity || 0 }}
                </template>
            </el-table-column>
            <el-table-column label="已入库数量" width="110" align="center">
                <template #default="{ row }">
                    <el-tag type="success">{{ row.inStockedQuantity || 0 }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="未入库数量" width="110" align="center">
                <template #default="{ row }">
                    <el-tag type="warning">{{ row.unStockedQuantity || 0 }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="本次入库量" width="110" align="center">
                <template #default="{ row }">
                    <el-tag type="primary">{{ row.thisTimeQuantity || 0 }}</el-tag>
                </template>
            </el-table-column>

            <!-- 位置信息 -->
            <el-table-column label="库位编码" width="100" align="center">
                <template #default="{ row }">
                    {{ row.stockPosition || '' }}
                </template>
            </el-table-column>
            <el-table-column label="库位名称" width="120" align="center">
                <template #default="{ row }">
                    {{ row.stockPositionName || '' }}
                </template>
            </el-table-column>

            <!-- 价格信息 -->
            <el-table-column label="进货单价" width="100" align="center">
                <template #default="{ row }">
                    <span style="color: #E6A23C;">{{ formatPrice(row.purchasePrice) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="入库金额" width="100" align="center">
                <template #default="{ row }">
                    <span style="color: #67C23A; font-weight: bold;">{{ formatPrice(row.upprice) }}</span>
                </template>
            </el-table-column>

            <!-- 批次和日期信息 -->
            <el-table-column label="批次号" width="120" align="center">
                <template #default="{ row }">
                    {{ row.batchNo || '' }}
                </template>
            </el-table-column>
            <el-table-column label="生产日期" width="110" align="center">
                <template #default="{ row }">
                    {{ formatDate(row.productionDate) }}
                </template>
            </el-table-column>
            <el-table-column label="过期日期" width="110" align="center">
                <template #default="{ row }">
                    {{ formatDate(row.expireDate) }}
                </template>
            </el-table-column>


            <!-- 其他信息 -->
            <el-table-column label="删除标识" width="100" align="center">
                <template #default="{ row }">
                    <el-tag :type="row.isDel ? 'danger' : 'success'">
                        {{ row.isDel ? '已删除' : '正常' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="备注" width="200" align="left" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.remark || '' }}
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 30, 50, 100]" :total="pagination.total" :background="true"
                layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();
const loading = ref(false);

// 统计数据
const statistics = reactive({
    totalOrders: 0,
    totalProducts: 0,
    totalAmount: 0
});

// 分页配置
const pagination = reactive({
    currentPage: 1,
    pageSize: 20, // 默认每页20条，与API默认值一致
    total: 0
});

// 表格数据
const tableData = ref([]);

// 弹窗控制
const fieldInfoVisible = ref(false);
const apiInfoVisible = ref(false);

// 当前API参数
const currentApiParams = ref({});

// 字段映射信息
const fieldMappings = ref([
    { displayName: '记录ID', fieldName: 'id', dataType: 'Number', description: '数据库主键，唯一标识每条记录' },
    { displayName: '入库单ID', fieldName: 'stockInOrderId', dataType: 'Number', description: '关联入库单主表的ID' },
    { displayName: '入库单号', fieldName: 'stockInCode', dataType: 'String', description: '入库单的编号，如 ST20251030091221' },
    { displayName: '货品ID', fieldName: 'goodsId', dataType: 'Number', description: '货品的唯一标识ID' },
    { displayName: '货品编号', fieldName: 'goodsCode', dataType: 'String', description: '货品的编码，如 HP0900' },
    { displayName: '货品名称', fieldName: 'goodsName', dataType: 'String', description: '货品的名称，如机械革命电脑' },
    { displayName: '规格型号', fieldName: 'specModel', dataType: 'String', description: '货品的规格型号，如300cm*180cm' },
    { displayName: '当前库存', fieldName: 'currentInventory', dataType: 'Number', description: '货品当前的库存数量' },
    { displayName: '进货数量', fieldName: 'purchaseQuantity', dataType: 'Number', description: '计划进货的数量' },
    { displayName: '已入库数量', fieldName: 'inStockedQuantity', dataType: 'Number', description: '已经入库的数量' },
    { displayName: '未入库数量', fieldName: 'unStockedQuantity', dataType: 'Number', description: '尚未入库的数量' },
    { displayName: '本次入库量', fieldName: 'thisTimeQuantity', dataType: 'Number', description: '本次操作入库的数量' },
    { displayName: '库位编码', fieldName: 'stockPosition', dataType: 'String', description: '存储位置的编码' },
    { displayName: '库位名称', fieldName: 'stockPositionName', dataType: 'String', description: '存储位置的名称' },
    { displayName: '进货单价', fieldName: 'purchasePrice', dataType: 'Number', description: '货品的进货单价' },
    { displayName: '入库金额', fieldName: 'upprice', dataType: 'String', description: '本次入库的总金额' },
    { displayName: '批次号', fieldName: 'batchNo', dataType: 'String', description: '货品的批次编号' },
    { displayName: '生产日期', fieldName: 'productionDate', dataType: 'Date', description: '货品的生产日期' },
    { displayName: '过期日期', fieldName: 'expireDate', dataType: 'Date', description: '货品的过期日期' },
    { displayName: '删除标识', fieldName: 'isDel', dataType: 'Boolean', description: '逻辑删除标识，true表示已删除' },
    { displayName: '备注', fieldName: 'remark', dataType: 'String', description: '备注信息' }
]);

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 获取入库类型文本
const getInboundTypeText = (type) => {
    if (type === 1) return '进货入库';
    if (type === 2) return '销售退货';
    return type || '进货入库';
};

// 格式化价格
const formatPrice = (price) => {
    if (!price) return '0.00';
    return parseFloat(price).toFixed(2);
};

// 显示字段信息弹窗
const showFieldInfo = () => {
    fieldInfoVisible.value = true;
};

// 显示API信息弹窗
const showApiInfo = () => {
    apiInfoVisible.value = true;
};

// 获取数据类型颜色
const getTypeColor = (dataType) => {
    switch (dataType) {
        case 'Number': return 'primary';
        case 'String': return 'success';
        case 'Date': return 'warning';
        case 'Boolean': return 'danger';
        default: return 'info';
    }
};

// 处理分页大小变化
const handleSizeChange = (val) => {
    pagination.pageSize = val;
    loadData();
};

// 处理当前页变化
const handleCurrentChange = (val) => {
    pagination.currentPage = val;
    loadData();
};

// 刷新数据
const handleRefresh = () => {
    loadData();
};

// 加载数据
const loadData = async () => {
    loading.value = true;
    try {
        // 构建查询参数 - 根据API文档的参数格式
        const params = {
            pageIndex: pagination.currentPage,
            pageSize: pagination.pageSize,
            stockInOrderId: '', // 入库单ID (可选)
            stockInCode: '',    // 入库单号 (可选)
            goodsId: '',        // 货品ID (可选)
            goodsCode: '',      // 货品编号 (可选)
            goodsName: '',      // 货品名称 (可选)
            batchNo: '',        // 批次号 (可选)
            stockPosition: '',  // 库位 (可选)
            keyword: ''         // 关键词 (可选)
        };

        // 保存当前API参数用于信息显示
        currentApiParams.value = { ...params };

        console.log('=== 发送入库统计API请求 ===');
        console.log('API接口: /api/ruku/items/list');
        console.log('请求参数:', params);

        const response = await proxy.http.get('/api/ruku/items/list', {
            params: params
        });

        console.log('=== 入库统计API返回完整数据 ===', response);
        console.log('response.status:', response?.status);
        console.log('response.code:', response?.code);
        console.log('response.data:', response?.data);
        console.log('response.message:', response?.message);

        // 处理API响应数据
        if (response && response.data) {
            let dataList = [];
            let total = 0;

            // 根据API响应结构解析数据
            if (Array.isArray(response.data)) {
                // 如果response.data直接是数组
                dataList = response.data;
                total = response.totalCount || response.total || dataList.length;
                console.log('✅ response.data 是数组，直接使用');
            } else if (response.data.data && Array.isArray(response.data.data)) {
                // 如果数据在response.data.data中
                dataList = response.data.data;
                total = response.data.totalCount || response.data.total || dataList.length;
                console.log('✅ response.data.data 是数组');
            } else if (typeof response.data === 'object') {
                // 如果是对象格式，尝试从不同字段获取数据
                dataList = response.data.items || response.data.list || response.data.rows || [];
                total = response.data.totalCount || response.data.total || response.data.count || dataList.length;
                console.log('✅ 从对象中提取数据数组');
            }

            console.log('=== 解析后的入库数据列表 ===', dataList);
            console.log('当前页数据条数:', dataList.length);
            console.log('总记录数:', total);
            console.log('当前页码:', pagination.currentPage);
            console.log('每页大小:', pagination.pageSize);

            // 设置表格数据
            tableData.value = dataList;
            pagination.total = total;

            // 如果返回数据为空但不是第一页，自动回到第一页
            if (dataList.length === 0 && pagination.currentPage > 1) {
                console.warn('⚠️ 当前页无数据，返回第一页');
                pagination.currentPage = 1;
                loadData();
                return;
            }

            // 计算统计数据
            calculateStatistics();

        } else {
            console.warn('API响应异常:', response);
            tableData.value = [];
            pagination.total = 0;
            resetStatistics();
        }
    } catch (error) {
        console.error('=== 加载入库统计数据失败 ===', error);
        console.error('错误详情:', error.message);
        console.error('错误堆栈:', error.stack);
        tableData.value = [];
        resetStatistics();
        if (proxy && proxy.$message) {
            proxy.$message.error('加载数据失败: ' + error.message);
        }
    } finally {
        loading.value = false;
    }
};

// 计算统计数据
const calculateStatistics = () => {
    if (tableData.value && tableData.value.length > 0) {
        console.log('📊 开始计算统计数据');
        console.log('第一条数据示例:', tableData.value[0]);
        console.log('📋 检查核心字段:', {
            id: tableData.value[0]?.id,
            stockInOrderId: tableData.value[0]?.stockInOrderId,
            stockInCode: tableData.value[0]?.stockInCode,
            goodsId: tableData.value[0]?.goodsId,
            goodsCode: tableData.value[0]?.goodsCode,
            goodsName: tableData.value[0]?.goodsName,
            specModel: tableData.value[0]?.specModel,
            currentInventory: tableData.value[0]?.currentInventory,
            purchaseQuantity: tableData.value[0]?.purchaseQuantity,
            inStockedQuantity: tableData.value[0]?.inStockedQuantity,
            unStockedQuantity: tableData.value[0]?.unStockedQuantity,
            thisTimeQuantity: tableData.value[0]?.thisTimeQuantity,
            stockPosition: tableData.value[0]?.stockPosition,
            stockPositionName: tableData.value[0]?.stockPositionName,
            purchasePrice: tableData.value[0]?.purchasePrice,
            upprice: tableData.value[0]?.upprice,
            batchNo: tableData.value[0]?.batchNo,
            productionDate: tableData.value[0]?.productionDate,
            expireDate: tableData.value[0]?.expireDate,
            remark: tableData.value[0]?.remark
        });

        // 统计入库单数量（去重）
        const stockInCodes = tableData.value
            .map(item => item.stockInCode)
            .filter(code => code && code.trim() !== '');
        const uniqueStockInCodes = new Set(stockInCodes);
        statistics.totalOrders = uniqueStockInCodes.size;

        // 统计入库货品数量 - 优先使用 thisTimeQuantity（本次入库量）
        statistics.totalProducts = tableData.value.reduce((sum, item) => {
            // 优先级：thisTimeQuantity > inStockedQuantity > purchaseQuantity
            const qty = parseFloat(item.thisTimeQuantity || item.inStockedQuantity || item.purchaseQuantity) || 0;
            console.log(`📦 商品数量: ${item.goodsName || '未知商品'} - thisTimeQuantity: ${item.thisTimeQuantity}, inStockedQuantity: ${item.inStockedQuantity}, purchaseQuantity: ${item.purchaseQuantity}, 使用数量: ${qty}`);
            return sum + qty;
        }, 0);

        // 统计入库货品金额 - 优先使用 upprice（入库金额），否则用单价×数量
        statistics.totalAmount = tableData.value.reduce((sum, item) => {
            let amount = 0;

            // 优先使用 upprice（入库金额）
            if (item.upprice) {
                amount = parseFloat(item.upprice) || 0;
                console.log(`💰 金额方式1 - ${item.goodsName}: 直接使用upprice = ${amount}`);
            } else {
                // 备选：进货单价 × 本次入库量
                const price = parseFloat(item.purchasePrice) || 0;
                const qty = parseFloat(item.thisTimeQuantity || item.inStockedQuantity || item.purchaseQuantity) || 0;
                amount = price * qty;
                console.log(`💰 金额方式2 - ${item.goodsName}: ${price} × ${qty} = ${amount}`);
            }

            return sum + amount;
        }, 0).toFixed(2);

        console.log('📈 统计结果:');
        console.log('  - 入库单数量:', statistics.totalOrders, '(基于 stockInCode 去重)');
        console.log('  - 入库货品数量:', statistics.totalProducts, '(基于 thisTimeQuantity > inStockedQuantity > purchaseQuantity)');
        console.log('  - 入库货品金额:', statistics.totalAmount, '(基于 upprice 或 purchasePrice × 数量)');
        console.log('🔍 核心字段统计:', {
            总数据条数: tableData.value.length,
            有thisTimeQuantity字段的数据: tableData.value.filter(item => item.thisTimeQuantity !== undefined).length,
            有inStockedQuantity字段的数据: tableData.value.filter(item => item.inStockedQuantity !== undefined).length,
            有purchaseQuantity字段的数据: tableData.value.filter(item => item.purchaseQuantity !== undefined).length,
            有upprice字段的数据: tableData.value.filter(item => item.upprice !== undefined).length,
            有purchasePrice字段的数据: tableData.value.filter(item => item.purchasePrice !== undefined).length,
            唯一入库单号数量: new Set(tableData.value.map(item => item.stockInCode).filter(code => code)).size
        });
    } else {
        resetStatistics();
    }
};

// 重置统计数据
const resetStatistics = () => {
    statistics.totalOrders = 0;
    statistics.totalProducts = 0;
    statistics.totalAmount = '0.00';
    console.log('📊 统计数据已重置');
};

// 页面加载时获取数据
onMounted(() => {
    loadData();
});
</script>

<style lang="less" scoped>
.inbound-statistics-container {
    padding: 20px;
    background-color: #f5f7fa;

    .statistics-cards {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;

        .stat-card {
            flex: 1;
            text-align: center;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            .stat-value {
                font-size: 32px;
                font-weight: bold;
                color: #409EFF;
                margin-bottom: 10px;
                line-height: 1.2;
            }

            .stat-value-green {
                color: #67C23A;
            }

            .stat-label {
                font-size: 14px;
                color: #606266;
                font-weight: 500;
            }
        }
    }

    .action-buttons {
        margin-bottom: 20px;
        display: flex;
        gap: 10px;
    }

    .el-table {
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
        background-color: #fff;
        padding: 16px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    // 字段信息弹窗样式
    .field-info-content {
        .json-viewer {
            .el-input {
                font-family: 'Courier New', monospace;
                font-size: 12px;
            }
        }

        .statistics-info {
            padding: 20px;
        }
    }

    // API信息弹窗样式
    .api-info-content {
        pre {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            border: 1px solid #e9ecef;
            overflow-x: auto;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
    }

    // 表格横向滚动优化
    .el-table {
        .el-table__body-wrapper {
            overflow-x: auto;
        }
    }
}
</style>
